package com.liuh.fram.util;

import com.alibaba.druid.filter.logging.Log4jFilter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.plugin.activerecord.IDataSourceProvider;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.plugin.druid.DruidPlugin;

/**
 * @note sql 常用处理
 * @author liuh
 */
public class SqlKit {

	/**
	 * @note 初始化c3p0
	 * @author liuh
	 */
	public IDataSourceProvider initC3p0(String url, String user, String pwd) {
		return new C3p0Plugin(url, user, pwd.trim());
	}

	/**
	 * @note 初始化druid
	 * @author liuh
	 */
	public IDataSourceProvider initDruid(String url, String user, String pwd) {
		DruidPlugin dp = new DruidPlugin(url, user, pwd);
		StatFilter statFilter = new StatFilter();
		statFilter.setLogSlowSql(true);
		statFilter.setMergeSql(true);
		statFilter.setSlowSqlMillis(10000);
		WallFilter wall = new WallFilter();
		wall.setDbType("mysql");
		dp.addFilter(statFilter);
		dp.addFilter(wall);
		dp.addFilter(new Log4jFilter());
		//
		dp.setMaxWait(60000L);
		dp.setMinEvictableIdleTimeMillis(300000L);
		return dp;
	}

	/**
	 * @note 生成预处理占位符
	 * @author liuh
	 */
	public static String preparePlaceHolders(int length) {
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < length;) {
			builder.append("?");
			if (++i < length) {
				builder.append(",");
			}
		}
		return builder.toString();
	}

}
